import { $ } from "./utils.js";
import {
	STORAGE_SYNC,
	MODE,
	ENABLE_PROXY,
	CONFIG_PAGE_TITLE,
	CONFIG_PAGE_RELATIVE_PATH,
	DATA_LIST,
	AUTO_RELOAD_PAGE,
} from "./constants.js";
import tabManager from "./manager/TabManager.js";
import ProxyManager from "./config/ProxyManager.js";
import { switchPopupIcon } from "./utils.js";

const proxyManager = new ProxyManager();
const { SYSTEM, FIXED_SERVERS } = chrome.proxy.Mode;
const systemProxyBtn = $("#system-proxy-btn");
const retweenProxyBtn = $("#retween-proxy-btn");
const proxyMsg = retweenProxyBtn.querySelector(".proxy-msg");
const retWeenProxyList = $("#retween-proxy-btn .proxy-list");
const settingsBtn = $("#settings-btn");
const tabsDom = $("#tabs");
const lis = Array.from(tabsDom.children);
const selectedClassName = "selected";

init();

systemProxyBtn.addEventListener("click", async () => {
	saveTabProxyInfo(SYSTEM);
});

retweenProxyBtn.addEventListener("click", async (e) => {
	const { enableProxy } = await STORAGE_SYNC.get(ENABLE_PROXY);
	console.log(enableProxy);

	if (!enableProxy) {
		window.close();
		settingsBtn.click();
		return;
	}
	saveTabProxyInfo(FIXED_SERVERS, enableProxy);
});

retweenProxyBtn.addEventListener("mouseenter", () => {
	document.body.style.paddingLeft = "220px";
});
retweenProxyBtn.addEventListener("mouseleave", () => {
	document.body.style.paddingLeft = "0";
});

settingsBtn.addEventListener("click", async () => {
	const tabs = chrome.tabs;
	const alreadyOpenTab = await tabs.query({ title: CONFIG_PAGE_TITLE });

	if (!alreadyOpenTab.length) {
		tabs.create({
			url: CONFIG_PAGE_RELATIVE_PATH,
		});
	} else {
		tabs.highlight({ tabs: alreadyOpenTab[0].index });
	}
});

async function init() {
	let { mode, enableProxy } = await STORAGE_SYNC.get([MODE, ENABLE_PROXY]);
	// 加载界面选项
	loadOptions(mode);
	// 加载ip列表
	loadRetWeenProxyList();

	if (!enableProxy) {
		return;
	}

	const queryTabs = await chrome.tabs.query({ active: true });
	const tabId = queryTabs[0].id;
	const proxyId = await tabManager.get(tabId);

	if (proxyId) {
		enableProxy = proxyManager.getProxy(proxyId);
	}

	proxyMsg.innerHTML = `${enableProxy.ip}:${enableProxy.port}`;
}

function loadOptions(mode) {
	lis.forEach((li) => {
		if (li.classList.contains(mode)) {
			li.classList.add(selectedClassName);
		}

		bindSelectedEvent(li, tabsDom);
	});
}

async function loadRetWeenProxyList() {
	const { dataList, enableProxy } = await STORAGE_SYNC.get([
		DATA_LIST,
		ENABLE_PROXY,
	]);

	if (!dataList.length) {
		return;
	}

	dataList.forEach((item) => {
		const li = document.createElement("li");
		const text = `${item.ip}:${item.port}`;
		const enableProxyText = `${enableProxy.ip}:${enableProxy.port}`;

		if (text === enableProxyText) {
			li.classList.add(selectedClassName);
		}

		li.innerHTML = text;

		bindSelectedEvent(li, retWeenProxyList);

		li.addEventListener("click", async (e) => {
			e.stopPropagation();
			saveTabProxyInfo(FIXED_SERVERS, item, true);
			proxyMsg.innerHTML = text;
		});

		retWeenProxyList.append(li);
	});
}

function bindSelectedEvent(li, container) {
	li.addEventListener("click", (e) => {
		e.stopPropagation();

		const curClassList = li.classList;

		if (curClassList.contains(selectedClassName)) {
			return;
		}

		const oldSelected = container.querySelector(`.${selectedClassName}`);

		if (oldSelected) {
			oldSelected.classList.remove(selectedClassName);
		}

		curClassList.add(selectedClassName);
		window.close();
	});
}

async function saveTabProxyInfo(mode, enableProxy = {}, enable = false) {
	STORAGE_SYNC.set({ mode });

	const [{ id: tabId }] = await chrome.tabs.query({ active: true });
	tabManager.put(tabId, enableProxy?.id);

	if (enable) {
		proxyManager.enableProxy(enableProxy.id);
	}

	switchPopupIcon(mode);
	reloadPage();
}

async function reloadPage() {
	// 自动刷新页面
	let { autoReloadPage } = await STORAGE_SYNC.get(AUTO_RELOAD_PAGE);

	if (!autoReloadPage) {
		return;
	}

	const activeTabs = await chrome.tabs.query({ active: true });
	if (activeTabs.length) {
		chrome.tabs.reload(activeTabs[0].id);
	}
}
